//
//  WFFarmLocationCell.m
//  WisdomFarm
//
//  Created by sky on 2017/11/13.
//  Copyright © 2017年 sky. All rights reserved.
//

#import "WFFarmLocationCell.h"
#import "MKMapView+ZoomLevel.h"
#import "WFLocationManager.h"

@interface WFFarmLocationCell()<MKMapViewDelegate>

@property (nonatomic, strong) MKPointAnnotation *annotation;
@property (nonatomic, strong) UILongPressGestureRecognizer *press;
@property (nonatomic, strong) CLGeocoder *geoCoder;



@end

@implementation WFFarmLocationCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        _titleView = [[UIView alloc] init];
        [self.contentView addSubview:_titleView];
        _mapView = [[MKMapView alloc] init];
        [self.contentView addSubview:_mapView];

        _titleButton = [[UIButton alloc] init];
        [self.titleView addSubview:_titleButton];
        _tipsLabel = [[UILabel alloc] init];
        [self.titleView addSubview:_tipsLabel];
        
        [_titleView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.top.offset(0);
            make.height.mas_equalTo(41);
        }];

        [_titleButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(15);
            make.centerY.offset(0);
        }];
        [self.titleButton setTitleColor:[UIColor textTitleColor] forState:UIControlStateNormal];
        [self.titleButton setImage:[UIImage imageNamed:@"home_edit_loction"] forState:UIControlStateNormal];
        [self.titleButton setTitle:@"农场位置" forState:UIControlStateNormal];
        self.titleButton.titleLabel.font = SCFont(14);
        
        [_tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.titleButton.mas_right).offset(9);
            make.centerY.offset(0);
        }];
        self.tipsLabel.text = @"(请将指针拖至农场所在位置)";
        self.tipsLabel.textColor = [UIColor textLightColor];
        self.tipsLabel.font = SCFont(14);
        
        [_mapView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.titleView.mas_bottom);
            make.left.right.bottom.offset(0);
        }];
        self.mapView.delegate = self;
        
        _press = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPress:)];
        _press.minimumPressDuration = 1.f;
        [self.mapView addGestureRecognizer:self.press];
    }
    return self;
}

- (void)dealloc {
    [self.mapView removeGestureRecognizer:self.press];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)onLongPress:(UILongPressGestureRecognizer *)press {
    if (press.state == UIGestureRecognizerStateBegan) {
        CLLocationCoordinate2D coordinate = [self.mapView convertPoint:[press locationInView:self.mapView] toCoordinateFromView:self.mapView];
        if (!CLLocationCoordinate2DIsValid(coordinate)) {
            return;
        }
        self.currentLocation = [[CLLocation alloc] initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    }
}

- (MKPointAnnotation *)annotation {
    if (!_annotation) {
        _annotation = [[MKPointAnnotation alloc] init];
        _annotation.coordinate = self.currentLocation ? self.currentLocation.coordinate : CLLocationCoordinate2DMake(30, 120);
    }
    return _annotation;
}

- (void)setCurrentLocation:(CLLocation *)currentLocation {
    _currentLocation = currentLocation;
    self.annotation.coordinate = currentLocation.coordinate;
    [self.mapView removeAnnotation:self.annotation];
    [self.mapView addAnnotation:self.annotation];
    [self.mapView showAnnotations:@[self.annotation] animated:YES];
    if (self.mapView.currentZoomLevel < 13) {
        [self.mapView setCenterCoordinate:currentLocation.coordinate zoomLevel:13 animated:YES];
    }
}

- (void)requestAddessForAnnotationView:(MKAnnotationView *)view {
    CLLocationCoordinate2D gcj = self.currentLocation.coordinate;
    CLLocation *location = [[CLLocation alloc] initWithLatitude:gcj.latitude longitude:gcj.longitude];
    @weakify(self);
    [WFLocationManager requestAddressByLocation:location
                                       complete:^(NSString *address) {
                                           @strongify(self);
                                           self.annotation.title = address;
                                           self.address = address;
                                           [self.mapView selectAnnotation:self.annotation animated:YES];
                                       }];
//    if (!self.geoCoder) {
//        self.geoCoder = [[CLGeocoder alloc] init];
//    }
//    [self.geoCoder cancelGeocode];
//    [self.geoCoder reverseGeocodeLocation:self.currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
//        if (placemarks.count == 0) {
//            return;
//        }
//        CLPlacemark *placemark = [placemarks firstObject];
//        self.annotation.title = [NSString stringWithFormat:@"%@%@%@",
//                                 placemark.thoroughfare ?: @"",
//                                 placemark.subThoroughfare ?: @"",
//                                 placemark.name ?: @""
//                                 ];
////        self.annotation.title = placemark.name ?: @"";
//        [self.mapView selectAnnotation:self.annotation animated:YES];
//    }];
}

//MARK:- mapview delegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    MKAnnotationView *view = [mapView dequeueReusableAnnotationViewWithIdentifier:@"AnnotationView"];
    if (!view) {
        view = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"AnnotationView"];
        view.image = [UIImage imageNamed:@"home_edit_loction"];
        view.canShowCallout = YES;
    }
    [self requestAddessForAnnotationView:view];
    return view;
}

- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated {
    [self.contentView endEditing:YES];
}

@end
